<template>
  <view>
    <!-- 加载中蒙版 -->
    <qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
    <!-- #ifdef MP-WEIXIN -->
    <!-- 顶部导航 -->
    <qmy-custom-navbar :title="'发布圈子'"></qmy-custom-navbar>
    <!-- #endif -->
    <view :style="{paddingTop:menuObject.top + menuObject.height + 15 +'px'}" class="page-content">
      <scroll-view scroll-y class="scroll-content">
        <view class="ping-30">
          <!-- 图片上传 -->
          <uni-file-picker ref="files" v-model="imgUrl" return-type="array" limit="6" mode="grid" file-mediatype="image"
            :sizeType="['compressed']"
            :image-styles="{width: '160rpx', height: '160rpx',border:false,background:'#f7f7f7',borderRadius:'20rpx',lineHeight:'160rpx'}">
          </uni-file-picker>
          <!-- 标题输入 -->
          <view class="input-box ali-item-cen flex-dir-row ali-item-cen flex-x-bet">
            <input confirm-type="done" placeholder-class="input-placeholder" type="text" v-model="title"
              placeholder="填写标题" cursor-color="#14cc60" :maxlength="23" class="w-100 fs-32 fw-600" />
            <text v-if="title" class="iconfont ic-qingchu fs-40 col-b1 mr-20 ml-20" @click="clearTitle"></text>
            <view class="fs-26 col-b1">{{23-title.length}}</view>
          </view>
          <!-- 多行内容输入 -->
          <view class="mt-30 textarea-box">
            <textarea placeholder-class="textarea-placeholder" :maxlength="230" v-model="content" placeholder="填写内容"
              cursor-color="#14cc60" class="w-100 fs-30" />
          </view>
          <view class="mt-30">
            <view class=" w-100 mt-30 bac-col-f ping-30-0 activity-box">
              <view class="w-100 flex-dir-row ali-item-cen flex-x-bet">
                <view class="flex-dir-row ali-item-cen">
                  <view class="fs-28 fw-600 col-0">关联话题</view>
                  <view class="fs-26 col-b1" v-if="selectedActivity.length > 0">（已选{{selectedActivity.length}}个）</view>
                </view>
                <view class="bor-bottom-f3 br-200 bac-col-f text-ali-c ping-0-20 fs-26" style="width: 340rpx;">
                  <input type="text" v-model="topicName" confirm-type="done"
                    placeholder-style="color:#b1b1b1;font-size:26rpx;text-align:center;" placeholder="输入话题查找" />
                </view>
              </view>
              <scroll-view scroll-x class="w-100 mt-20">
                <view class="flex-dir-row">
                  <view class="flex-dir-row ali-item-cen mr-20 flex-shrink-0" v-for="(item, index) in filteredTopicList"
                    :key="index" @click="topicClick(item.id)">
                    <view style="height: 55rpx;line-height: 55rpx;"
                      :class="selectedActivity.includes(item.id) ? 'bac-col-00b col-f' : 'activity-item'"
                      class="br-10 flex-dir-row ali-item-cen pr-20 topic-item">
                      <image :src="item.coverImage"
                        style="width: 55rpx; height: 55rpx;border-top-left-radius: 10rpx;border-bottom-left-radius: 10rpx;"
                        mode="aspectFill" />
                      <view class="fs-28 ml-20 text-element-1 flex-1">{{ item.name }}</view>
                      <!-- 选中状态图标 -->
                      <view v-if="selectedActivity.includes(item.id)" class="selected-icon">
                        <text class="iconfont ic-xuanzhong fs-24 col-f"></text>
                      </view>
                    </view>
                  </view>
                </view>
              </scroll-view>
              <!-- 已选择的话题列表 -->
              <view v-if="selectedActivity.length > 0" class="selected-topics mt-20">
                <view class="flex-dir-row ali-item-cen flex-x-bet mb-10">
                  <view class="fs-26 col-666">已选择的话题：</view>
                  <view class="clear-all-btn" @click="clearAllTopics">
                    <text class="fs-24 col-999">清空全部</text>
                  </view>
                </view>
                <view class="flex-dir-row flex-wrap">
                  <view v-for="topicId in selectedActivity" :key="topicId" class="selected-topic-tag mr-10 mb-10"
                    @click="removeSelectedTopic(topicId)">
                    <text class="fs-24 col-00b">{{ getTopicNameById(topicId) }}</text>
                    <text class="iconfont ic-qingchu fs-20 col-00b ml-5"></text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 添加标签选择 -->
          <view class="mt-30">
            <view class="w-100 mt-30 bac-col-f ping-30-0 activity-box">
              <view class="w-100 flex-dir-row ali-item-cen flex-x-bet">
                <view class="flex-dir-row ali-item-cen">
                  <view class="fs-28 fw-600 col-0">添加标签</view>
                  <view class="fs-26 col-b1" v-if="selectedTags.length > 0">（已选{{selectedTags.length}}个）</view>
                </view>
                <view class="bor-bottom-f3 br-200 bac-col-f text-ali-c ping-0-20 fs-26" style="width: 340rpx;">
                  <input type="text" v-model="searchTag" confirm-type="done"
                    placeholder-style="color:#b1b1b1;font-size:26rpx;text-align:center;" placeholder="输入标签名称查找" />
                </view>
              </view>
              <scroll-view scroll-x class="w-100 mt-20">
                <view class="flex-dir-row">
                  <view class="flex-dir-row ali-item-cen mr-20 flex-shrink-0" v-for="(item, index) in filteredTagList"
                    :key="index" @click="tagClick(item.name)">
                    <view style="height: 50rpx;line-height: 50rpx;"
                      :class="selectedTags.includes(item.name) ? 'bac-col-00b col-f' : 'activity-item'"
                      class="br-10 flex-dir-row ali-item-cen pr-20 topic-item">
                      <view class="fs-28 ml-20 text-element-1 flex-1">#{{ item.name }}</view>
                      <!-- 选中状态图标 -->
                      <view v-if="selectedTags.includes(item.name)" class="selected-icon">
                        <text class="iconfont ic-xuanzhong fs-24 col-f"></text>
                      </view>
                    </view>
                  </view>
                </view>
              </scroll-view>
              <!-- 已选择的标签列表 -->
              <view v-if="selectedTags.length > 0" class="selected-topics mt-20">
                <view class="flex-dir-row ali-item-cen flex-x-bet mb-10">
                  <view class="fs-26 col-666">已选择的标签：</view>
                  <view class="clear-all-btn" @click="clearAllTags">
                    <text class="fs-24 col-999">清空全部</text>
                  </view>
                </view>
                <view class="flex-dir-row flex-wrap">
                  <view v-for="tagName in selectedTags" :key="tagName" class="selected-topic-tag mr-10 mb-10"
                    @click="removeSelectedTag(tagName)">
                    <text class="fs-24 col-00b">#{{ tagName }}</text>
                    <text class="iconfont ic-qingchu fs-20 col-00b ml-5"></text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 底部定位发布按钮 -->
    <view class="w-100 fixed-bottom bac-col-00b" @click="publish">
      <view class="w-100 bg-col-00b text-ali-c">
        <view class="fs-30 col-f fw-600">{{ circleId ? '修改圈子' : '发布圈子' }}</view>
      </view>
    </view>
  </view>
</template>



<script>
  import {
    getTopicListApi
  } from '@/api/topic/topic.js';
  import {
    publishPostApi,
    getMyCircleDetailApi,
    updateCircleDataApi
  } from "../../api/post/posts";
  import {
    getTagListApi
  } from '@/api/activity/activityTag.js';
  export default {
    data() {
      return {
        title: '', // 标题
        content: '', // 内容
        // #ifdef MP-WEIXIN
        menuObject: uni.getMenuButtonBoundingClientRect(),
        // #endif
        // #ifndef MP-WEIXIN
        menuObject: 0,
        // #endif // 菜单按钮位置
        selectedActivity: [], // 选中的话题id数组，支持多选
        selectedTags: [], // 选中的标签数组
        imgUrl: [], // 图片上传
        topicList: [], // 话题列表
        topicName: '', // 搜索框输入的内容
        tagList: [], // 标签列表
        searchTag: '', // 搜索标签
        circleId: '', // 圈子id
        dataLoaded: true, // 数据是否加载完成
      };
    },
    computed: {
      // 计算筛选后的话题列表
      filteredTopicList() {
        if (!this.topicName.trim()) {
          // 如果输入框为空，返回全部列表
          return this.topicList;
        }
        const searchText = this.topicName.toLowerCase(); // 转换为小写
        return this.topicList.filter(item => item.name.toLowerCase().includes(searchText));
      },
      // 计算筛选后的标签列表
      filteredTagList() {
        if (!this.searchTag.trim()) {
          return this.tagList;
        }
        return this.tagList.filter(item => item.name.includes(this.searchTag));
      }
    },
    onLoad(e) {
      if (e.id) {
        this.circleId = e.id;
        // 如果存在圈子id则为修改，获取圈子详情
        this.getCircleDetail();
      }
      // 获取话题列表
      this.getTopicList();
      // 获取标签列表
      this.getTagList();
    },
    methods: {
      // 获取圈子详情
      getCircleDetail() {
        getMyCircleDetailApi(this.circleId).then((res) => {
          const circleData = res.data.data || res.data;
          this.circleData = circleData;
          this.imgUrl = circleData.images ? JSON.parse(circleData.images) : [];
          this.title = circleData.title;
          this.content = circleData.content;
          // 处理话题数据，支持多选
          if (circleData.topics) {
            // 解析JSON格式的话题ID数组
            try {
              const topicIds = typeof circleData.topics === 'string' ? JSON.parse(circleData.topics) : circleData
                .topics;
              this.selectedActivity = Array.isArray(topicIds) ? topicIds : [];
            } catch (e) {
              this.selectedActivity = [];
            }
          }
          // 处理标签数据，支持多选
          if (circleData.tags) {
            // 解析JSON格式的标签数组
            try {
              const tags = typeof circleData.tags === 'string' ? JSON.parse(circleData.tags) : circleData.tags;
              this.selectedTags = Array.isArray(tags) ? tags : [];
            } catch (e) {
              this.selectedTags = [];
            }
          }
          if (!this.imgUrl || this.imgUrl.length === 0) {
            this.$Toast('该圈子为管理端发布，请到管理端编辑');
            setTimeout(() => this.$NavigateBack(), 1600)
            return;
          }
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
        });
      },
      // 获取话题列表
      getTopicList() {
        getTopicListApi().then((res) => {
          this.topicList = res.data.data;
          console.log("发布圈子可选择的话题表数据：", this.topicList);
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
        });
      },
      // 获取标签列表
      getTagList() {
        getTagListApi().then(res => {
          this.tagList = res.data.data;
          console.log("发布圈子可选择的标签数据：", this.tagList);
        }).catch(err => {
          console.error('获取标签列表失败:', err);
          let {
            code,
            msg
          } = this.$parseError(err);
          this.$Toast(msg);
        });
      },
      // 选中话题（支持多选）
      topicClick(id) {
        const index = this.selectedActivity.indexOf(id);
        if (index > -1) {
          // 如果已选中，则取消选中
          this.selectedActivity.splice(index, 1);
        } else {
          // 如果未选中，则添加到选中列表
          this.selectedActivity.push(id);
        }
      },

      // 选中标签（支持多选）
      tagClick(tagName) {
        const index = this.selectedTags.indexOf(tagName);
        if (index > -1) {
          // 如果已选中，则取消选中
          this.selectedTags.splice(index, 1);
        } else {
          // 如果未选中，则添加到选中列表
          this.selectedTags.push(tagName);
        }
      },

      // 移除已选择的标签
      removeSelectedTag(tagName) {
        const index = this.selectedTags.indexOf(tagName);
        if (index > -1) {
          this.selectedTags.splice(index, 1);
        }
      },

      // 清空所有选中的标签
      clearAllTags() {
        uni.showModal({
          title: '提示',
          content: '确定要清空所有已选择的标签吗？',
          success: (res) => {
            if (res.confirm) {
              this.selectedTags = [];
              this.$Toast('已清空所有标签');
            }
          }
        });
      },

      // 移除已选择的话题
      removeSelectedTopic(topicId) {
        const index = this.selectedActivity.indexOf(topicId);
        if (index > -1) {
          this.selectedActivity.splice(index, 1);
        }
      },

      // 根据话题ID获取话题名称
      getTopicNameById(topicId) {
        const topic = this.topicList.find(item => item.id === topicId);
        return topic ? topic.name : '未知话题';
      },

      // 清空标题
      clearTitle() {
        this.title = '';
      },

      // 清空所有选中的话题
      clearAllTopics() {
        uni.showModal({
          title: '提示',
          content: '确定要清空所有已选择的话题吗？',
          success: (res) => {
            if (res.confirm) {
              this.selectedActivity = [];
              this.$Toast('已清空所有话题');
            }
          }
        });
      },
      // 发布圈子
      async publish() {
        this.$debounce(async () => {
          // 震动
          uni.vibrateShort();
          // 先校验用户所有参数，如果参数不完整，返回并提示用户
          if (this.imgUrl.length == 0) {
            this.$Toast('请上传图片');
            return;
          }
          if (this.title.trim() == '') {
            this.$Toast('请填写标题');
            return;
          }
          if (this.content.trim() == '') {
            this.$Toast('请填写内容');
            return;
          }
          if (this.selectedActivity.length == 0) {
            this.$Toast('请选择至少一个话题');
            return;
          }
          // 如果存在圈子id，则为修改
          if (this.circleId) {
            this.updateCircle();
          } else {
            this.addCircle();
          }
        }, 500, true, "publish")
      },
      // 修改圈子
      async updateCircle() {
        await updateCircleDataApi({
          id: this.circleId,
          title: this.title,
          content: this.content,
          topicIds: this.selectedActivity, // 支持多个话题ID
          tags: JSON.stringify(this.selectedTags), // 标签数组
          imgs: this.imgUrl
        }).then((res) => {
          this.$Toast(res.msg);
          this.getOpenerEventChannel().emit('refreshData', '')
          setTimeout(() => this.$NavigateBack(), 1000)
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
          setTimeout(() => {
            if (code === 401) {
              this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
            }
          }, 1000);
        });
      },
      // 添加圈子
      async addCircle() {
        await publishPostApi({
          title: this.title,
          content: this.content,
          topicIds: this.selectedActivity, // 支持多个话题ID
          tags: JSON.stringify(this.selectedTags), // 标签数组
          imgs: this.imgUrl
        }).then((res) => {
          this.$Toast('发布成功');
          setTimeout(() => {
            this.$NavigateTo('/pages/index/index');
          }, 1500);
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
          setTimeout(() => {
            if (code === 401) {
              this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
            }
          }, 1000);
        });
      }
    }
  };
</script>

<style lang="scss">
  .upload-image {
    width: 170rpx;
    height: 170rpx;

    .upload-image-item {
      line-height: 170rpx;
    }
  }

  .input-box {
    width: 100%;
    height: 90rpx;
    border-bottom: 1rpx solid #f3f3f3;
  }

  .input-placeholder {
    font-size: 30rpx;
    color: #b1b1b1;
    font-weight: normal;
  }

  .textarea-placeholder {
    font-size: 28rpx;
    color: #b1b1b1;
    font-weight: normal;
  }

  .textarea-box {
    height: 300rpx;
  }

  .activity-box {
    border-top: 1rpx solid #f3f3f3;
  }

  .activity-item {
    border-radius: 10rpx;
    background-color: #f7f7f7;
  }

  .fixed-bottom {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding-top: 30rpx;
    padding-bottom: 30rpx !important;
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
    z-index: 9999;
    transition: background-color 0.2s ease;
  }

  .fixed-bottom:active {
    background-color: #11b051 !important;
    /* 点击时背景颜色变化 */
  }

  .page-content {
    height: calc(100vh - var(--window-top) - 140rpx);
    /* 减去顶部导航和底部按钮的高度 */
    display: flex;
    flex-direction: column;
  }

  .scroll-content {
    flex: 1;
    height: 100%;
  }

  textarea {
    height: 300rpx !important;
  }

  /* 话题选择相关样式 */
  .topic-item {
    position: relative;
    transition: all 0.2s ease;
  }

  .topic-item:active {
    transform: scale(0.98);
  }

  .selected-icon {
    position: absolute;
    right: 5rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 30rpx;
    height: 30rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .selected-topics {
    padding: 20rpx;
    background-color: #f8f9fa;
    border-radius: 10rpx;
    border: 1rpx solid #e9ecef;
  }

  .selected-topic-tag {
    display: flex;
    align-items: center;
    padding: 8rpx 15rpx;
    background-color: #e8f5e8;
    border: 1rpx solid #00b050;
    border-radius: 20rpx;
    transition: all 0.2s ease;
  }

  .selected-topic-tag:active {
    background-color: #d4edda;
    transform: scale(0.95);
  }

  .flex-wrap {
    flex-wrap: wrap;
  }

  .col-666 {
    color: #666666;
  }

  .mb-10 {
    margin-bottom: 10rpx;
  }

  .ml-5 {
    margin-left: 5rpx;
  }

  .clear-all-btn {
    padding: 5rpx 15rpx;
    border: 1rpx solid #ddd;
    border-radius: 15rpx;
    background-color: #fff;
    transition: all 0.2s ease;
  }

  .clear-all-btn:active {
    background-color: #f5f5f5;
    transform: scale(0.95);
  }

  .col-999 {
    color: #999999;
  }
</style>